package sap.feed.android.demo;

import java.util.ArrayList;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Application;
import android.os.Handler;
import android.os.Message;
import sap.feed.java.client.SAPFeed;
import sap.feed.java.client.SAPFeedInterface;

public class BusLocationDemoService extends Application implements SAPFeedInterface{
	
	public SAPFeed feed;
	public Handler activityHandler;
	public ArrayList<Integer> datasetList;

	@Override
	public void onCreate(){
		datasetList = new ArrayList<Integer>();
		datasetList.add(11);

//		feed = new SAPFeed("http://10.33.247.66:8000/",this, 31, "aaa");
		feed = new SAPFeed("http://10.33.247.153:8000/",this, 31, "aaa");

	}
	
	public void onSAPFeedLogin() {
		// TODO Auto-generated method stub
		Message msg = new Message();
		JSONObject obj = new JSONObject();
		try {
			obj.put("type", "Login Success");
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		msg.obj = obj;
		activityHandler.sendMessage(msg);
		feed.listen(datasetList);

	}

	public void onSAPFeedLogout() {
		// TODO Auto-generated method stub
		
	}

	public void onSAPFeedPublish() {
		// TODO Auto-generated method stub
		
	}

	public void onSAPFeedReceive(int publisherID, int datasetID, Object obj) {

		// TODO Auto-generated method stub
		JSONObject data = (JSONObject)obj;

		Message msg = new Message();
		JSONObject passOn = new JSONObject();
		try {
			passOn.put("type", "Receive Message");
			passOn.put("target", data.getInt("target"));
			passOn.put("id", data.getInt("id"));
			passOn.put("distance", data.getInt("distance"));
			passOn.put("awt", data.getInt("awt"));
			passOn.put("seat", data.getString("seat"));
			passOn.put("dsID", datasetID);
			passOn.put("pubID", publisherID);

		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		msg.obj = passOn;
		activityHandler.sendMessage(msg);			
		
	}
	
	public void onSAPFeedListen() {
		// TODO Auto-generated method stub	
	}

	public void onSAPFeedError(String errorCode, String message) {
		
		// TODO Auto-generated method stub
		
		if(errorCode.equals("E999")){
			message = "You have unsubscribed from the data stream, application will resume when you re-subscribe to it";
		}
		
		Message msg = new Message();
		JSONObject obj = new JSONObject();
		try {
			obj.put("type", "Add Message");
			obj.put("title", errorCode);
			obj.put("text",message);
			
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		msg.obj = obj;
		activityHandler.sendMessage(msg);		
	}

	public void registerHandler(Handler handler){
		activityHandler = handler;
	}
}
